//
//  WBUserAccount.swift
//  CustomWeiBo
//
//  Created by laiqiang on 21/5/18.
//  Copyright © 2021年 laiqiang. All rights reserved.
//

import UIKit

fileprivate let filePath: String = "user_account.json"

class WBUserAccount: NSObject {

    //访问令牌
    var account_token: String?
    //用户id
    var uid: String? //"uid": 6373441203
    
    var screen_name: String?
    var avatar_large: String?
    
    //过期日期
    var expiresDate: Date?
    
    var userExpires_in: TimeInterval = 0
    //令牌的生命周期
    //开发者5年，使用者3天 从第一次算起
    var expires_in: TimeInterval {
        
        set{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
            self.userExpires_in = expires_in;
        }
        get{
            return self.userExpires_in
        }
    }
    
    override var description: String{
        return yy_modelDescription()
    }
    
    override init() {
        
        super.init()
        
        //取出文件
        let dire = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let path = (dire as NSString).appendingPathComponent(filePath)
        guard let datastr = NSData.init(contentsOfFile: path),
            let data  = try?JSONSerialization.jsonObject(with: datastr as Data, options:[]) as? [String : AnyObject]
        else {
            return
        }
        
        //设置属性
        yy_modelSet(withJSON: data ?? [:])
        
        //FIXME:
        return
        
        //过期处理
//        expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        if expiresDate?.compare(Date()) == .orderedDescending {
            //账户过期，清空 属性信息,删除帐户json文件
            account_token = nil
            uid = nil
            try?FileManager.default.removeItem(atPath: path)
        }
    }
    
    /**
     偏好 userdefault
     沙盒－归档keyArchiver／plish／json
     数据库 FMDB /core data
     钥匙串 SSKeychain
     /Users/laiqiang/Desktop/NewWeiBo/CustomWeiBo/CustomWeiBo/Class/Model/WBUserAccount.swift:53:28: Cast from 'Data?' to unrelated type 'NSData' always fails
     
     */
    func saveAccount() {

        //FIX:假数据
        account_token = "2.00lM_1xGahuflB1d3e0e6011rbuYkD"
        //用户id
        uid = "6373441203"
        screen_name = "小强6373441203"
        avatar_large = "https://tvax1.sinaimg.cn/default/images/default_avatar_male_180.gif?KID=imgbed,tva&Expires=1621790561&ssig=SiiAp%2BpxW2"
        
        
        let dire = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let path = (dire as NSString).appendingPathComponent(filePath)

        guard let new_data = self.yy_modelToJSONData(),
            let dataStr = NSString.init(data: new_data, encoding: String.Encoding.utf8.rawValue)
            else {
            return
        }
        
        //函数的尾部存在 “throws”，前面一定使用“try？”修饰，参数需要解包的，前面使用guard 守护一下，确保数据存在，就不用！强行解包了
        try?dataStr.write(toFile: path, atomically: true, encoding: String.Encoding.utf8.rawValue)
    }
}
